package com.xjggb.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.xjggb.cloud.entity.CommonResult;
import com.xjggb.cloud.entity.Payment;
import com.xjggb.cloud.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class CircleBreakerController {

    public  static  final String SERVER_URL="http://nacos-payment-provider";


    @Autowired
    private RestTemplate restTemplate;
    private Long id;

    @GetMapping("/consumer/fallback/{id}")
    //@SentinelResource(value = "fallback") //无配置
    //@SentinelResource(value = "fallback",fallback = "handlerFallback")//fallback只负责业务异常
   // @SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规
    @SentinelResource(value = "fallback",blockHandler = "blockHandler",fallback = "handlerFallback")
    public CommonResult show(@PathVariable("id") Long id) throws IllegalAccessException {
        CommonResult result = restTemplate.getForObject(SERVER_URL + "/payment/" + id, CommonResult.class, id);

        if (id==4){
            throw  new IllegalAccessException("IllegalAccessException非法参数异常");
        }else if (result.getData()==null){
            throw  new NullPointerException("NullPointerException,该id没有对应记录，空指针异常");
        }
        return result;

    }
    //fallback的兜底方法
    public CommonResult<Payment> handlerFallback(@PathVariable("id") Long id, Throwable throwable){
        Payment payment = new Payment(404L, "页面找不到");
        return new CommonResult<>(400,"兜底异常类"+throwable.getMessage(),payment);
    }
   //本例是blockHandler的兜底
   public CommonResult blockHandler(@PathVariable Long id, BlockException e){
       Payment payment = new Payment(id,"null");
       return new CommonResult<>(444,"blockHandler-sentinel限流,无此流水,BlockException: "+ e.getMessage(),payment);
   }


   @Resource
   private PaymentService paymentService;

    @GetMapping(value = "/consumer/payment/{id}")
    public CommonResult<Payment> show3(@PathVariable("id") Long id){

       return paymentService.show(id);
    }



}
